package gw.com.android.ui.trade.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import org.json.JSONException;

import butterknife.BindView;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.ui.trade.TradeRangeModel;
import gw.com.android.ui.views.OrderBottomView;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DoubleConverter;
import www.com.library.util.StringFormatter;

/**
 * 设置止损止盈界面
 *
 * @author reeta.zou
 *
 */
public class MarketOrderModifyFragment extends BaseOrderFragment {

	/**产品名称*/
	@BindView(R.id.proNameView)
	TextView mPrdNameView;

	/**订单id*/
	private int mOrderID = 0;

	/**
	 * 更新通知处理
	 */
	private final Handler HandlerCallback = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case GTSConst.REPLY_SYMBOL_TICK_UPDATE:
					// 更新界面价格和范围值
					mBottomview.updateProduct(mRangeModel);
					checkError();
					break;
			}
		}
	};

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		if (args != null) {
			mOrderID = args.getInt("id");
			mUiCode = args.getInt("uiCode");
			mPositionModel = DataManager.instance().getPositionModel(mOrderID);
			mTickModel = DataManager.instance().getTickModel(mUiCode);
			updateSymbolModel();
			if (null == mPositionModel || 0 == mUiCode || null == mSymbolModel) {
				Logger.e("设置止损止盈 mPositionModel对象为空，出现异常"+ mUiCode);
				if (null != getActivity()) {
					getActivity().finish();
				} else {
					AppActivities.getSingleton().currentActivity().finish();
				}
				return;
			}
			mSymbol = DataManager.instance().getPrdName(mPositionModel);
			if (mPositionModel.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_BUY) {
				mTradeDir = AppContances.TRADE_TYPE_SALE;
			} else {
				mTradeDir = AppContances.TRADE_TYPE_BUY;
			}
		}
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_order_modify_market;
	}

	@Override
	protected void initLayoutView() {
		super.initLayoutView();
		mBottomview.setPriceType(true);
		String str = AppMain.getAppString(R.string.order_type_modify_market);
		m_ConfirmButton.setText("#" + mOrderID + str);
		mBottomview.setErrorCheckLisenter(new OrderBottomView.onErrorCheckLisenter() {

			@Override
			public void onErrorCheck() {
				checkError();
			}
		});
		mRangeModel = new TradeRangeModel();
		cmd = AppContances.ORDER_TYPE_MODIFY;
	}

	@Override
	protected void initViewData() {
		mPrdNameView.setText(mSymbol);
		TradeBusiness.calLossAndWin2(mTickModel,mSymbolModel,mRangeModel,mPositionModel.getInt(GTSConst.JSON_KEY_DIRECTION));
		mBottomview.setProductInfo(mRangeModel);
		if (null != mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS) && !mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS).isEmpty()
				&& DoubleConverter.toFloatData(mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS)) > 0) {
			mDetail.setStringValue("mPreLoss", mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS));
			mBottomview.setLossValue(mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS));
		}
		if (null != mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT) && !mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT).isEmpty()
				&& DoubleConverter.toFloatData(mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT)) > 0) {
			mDetail.setStringValue("mPreWin", mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT));
			mBottomview.setProfitValue(mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT));
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		mBottomview.onFocusChanged(v, hasFocus);
		checkError();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			checkError();
		}
	}

	/**
	 * 检查界面错误
	 * @return
	 */
	private boolean checkError() {
		String errorMessage = "";
//		//检查止损止盈
		errorMessage = mBottomview.checkError();

		if (isVisible() && null != mStatusListener) {
			mStatusListener.onError(errorMessage);
		}

		if(!"".equals(errorMessage)) {
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 市价开仓前各种条件判断  
	 * @return
	 */
	public boolean hasPostData() {

		mBottomview.clearAllFocus();

		if (checkError()) {
			return false;
		}

		if (!TradeBusiness.PreOrderCheck(getActivity(), mPositionModel.getInt(GTSConst.JSON_KEY_ZONE), mPositionModel.getInt(GTSConst.JSON_KEY_TRADESTATE), false)) {
			return false;
		}

		try {
			mSeq = GTSDataListener.curSeq++;
			GTSDataListener.instance().addSeqList(mSeq+"", cmd+"");
			Logger.e("设置止损止盈的seq == " + mSeq);
			jsonData.put(GTSConst.JSON_KEY_ID, mPositionModel.getInt(GTSConst.JSON_KEY_ID));
			jsonData.put(GTSConst.JSON_KEY_CODEID,mPositionModel.getInt(GTSConst.JSON_KEY_CODEID));
			jsonData.put(GTSConst.JSON_KEY_DIRECTION, mPositionModel.getInt(GTSConst.JSON_KEY_DIRECTION));
			jsonData.put(GTSConst.JSON_KEY_EXPIRETYPE, AppContances.VALID_TYPE_DAY);
			jsonData.put(GTSConst.JSON_KEY_ORDERPRICE, mPositionModel.getString(GTSConst.JSON_KEY_OPENPRICE));
			jsonData.put(GTSConst.JSON_KEY_ORDERTYPE, mPositionModel.getInt(GTSConst.JSON_KEY_ORDERTYPE));
			jsonData.put(GTSConst.JSON_KEY_STOPLOSS, mBottomview.getLossPrice());
			jsonData.put(GTSConst.JSON_KEY_STOPPROFIT, mBottomview.getWinPrice());
			jsonData.put(GTSConst.JSON_KEY_TRADE_SEQ, mSeq);
		}catch (JSONException e){
			e.printStackTrace();
		}

		if (!DoubleConverter.isZero(DoubleConverter.toFloatData(jsonData.optString(GTSConst.JSON_KEY_STOPLOSS)))) {
			mDetail.setStringValue("mLoss", jsonData.optString(GTSConst.JSON_KEY_STOPLOSS));
		} else {
			mDetail.setStringValue("mLoss", "");
		}
		if (!DoubleConverter.isZero(DoubleConverter.toFloatData(jsonData.optString(GTSConst.JSON_KEY_STOPPROFIT)))) {
			mDetail.setStringValue("mWin",jsonData.optString(GTSConst.JSON_KEY_STOPPROFIT));
		} else {
			mDetail.setStringValue("mWin", "");
		}

		if (DoubleConverter.isEqual(DoubleConverter.toFloatData(mDetail.getString("mPreLoss")),DoubleConverter.toFloatData(mDetail.getString("mLoss")), mSymbolModel.getInt(GTSConst.JSON_KEY_DIGITS))
				&& DoubleConverter.isEqual(DoubleConverter.toFloatData(mDetail.getString("mPreWin")),DoubleConverter.toFloatData(mDetail.getString("mWin")), mSymbolModel.getInt(GTSConst.JSON_KEY_DIGITS))) {
			String errorMessage = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1029);
			showToastPopWindow(errorMessage);
			return false;
		}

		mDetail.setStringValue("mCurrentTag", AppContances.TAB_ID_MODIFY_ORDER);
		mDetail.setIntValue("mPrdCode", mUiCode);
		mDetail.setIntValue("mPositionID", mOrderID);
		mDetail.setStringValue("mSymbol", mSymbol);

		return true;
	}

	@Override
	public void requstData() {
		int result = AppTerminal.instance().reqOrder(cmd, jsonData.toString());
		if(result != 0){
			if(null != mStatusListener){
				mStatusListener.onFail();
			}
			if(result == 97){
				PopupConfirmDialog.NotifyPrompt(getActivity(), ConfigUtil.instance().mErrorConfigObject.optString(ConfigType.SERVER_ERROR_1016));
			}else{
				PopupConfirmDialog.NotifyPrompt(getActivity(), ConfigUtil.instance().mErrorConfigObject.optString(ConfigType.SERVER_ERROR_1068));
			}
		}
	}

	@Override
	public void onSymbolNotify(DataItemDetail tickModel) {
		if(null != tickModel && mUiCode == tickModel.getInt(GTSConst.JSON_KEY_CODEID)){
			mTickModel = tickModel;
			if(null != mRangeModel){
				TradeBusiness.calLossAndWin2(mTickModel,mSymbolModel,mRangeModel,mPositionModel.getInt(GTSConst.JSON_KEY_DIRECTION));
				HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_TICK_UPDATE);
			}
		}
	}

	@Override
	public void onSymbolNotify() {
		super.onSymbolNotify();
		updateSymbolModel();
	}

	@Override
	public void onOrderSuccessNotify(int notifyId, int orderId, DataItemDetail model) {
		if (mSeq == notifyId) {
			Logger.e("设置止损止盈成功 orderId = " + orderId + " notifyId == " + notifyId);
			if (null != model) {
				mDetail.setStringValue("mTime", StringFormatter.instance().secToDateTime(model.getInt(GTSConst.JSON_KEY_POS_UPDATETIME)));
				if (!DoubleConverter.isZero(DoubleConverter.toFloatData(model.getString(GTSConst.JSON_KEY_STOPLOSS)))) {
					mDetail.setStringValue("mLoss", model.getString(GTSConst.JSON_KEY_STOPLOSS));
				} else {
					mDetail.setStringValue("mLoss", "");
				}
				if (!DoubleConverter.isZero(DoubleConverter.toFloatData(model.getString(GTSConst.JSON_KEY_STOPPROFIT)))) {
					mDetail.setStringValue("mWin",model.getString(GTSConst.JSON_KEY_STOPPROFIT));
				} else {
					mDetail.setStringValue("mWin", "");
				}

				if (null != mStatusListener) {
					Logger.e("onFragmentPositionUpdate 设置止损止盈成功 mStatusListener ");
					mStatusListener.onSuc(mDetail);
				}
			}
		}
	}
}